import React, { forwardRef, useImperativeHandle } from 'react';
import { Bar, Pie } from '@ant-design/plots';

import moment from 'moment';
import { useState, useMemo } from 'react';
import { useEffect } from 'react';
import { Card, Radio, Form, Input } from 'antd';
import loginService from '@/services/loginService';

// import { Pie as G2plotPie } from '@antv/Charts';
import { useRef } from 'react';
import { Chart } from '@antv/g2';
import type { Chart as ChartType } from '@antv/g2';
const MyChart = forwardRef((props, ref) => {
  const chartInstance = useRef<ChartType>();
  const el = useRef(null);

  useImperativeHandle(ref, () => ({
    chart: chartInstance.current,
  }));
  const { data } = props;

  useEffect(() => {
    if (!el.current) return;
    if (chartInstance.current) {
      chartInstance.current?.destroy?.();
    }

    const chart = new Chart({
      container: el.current,
      autoFit: true,
      height: 500,
      padding: [50, 20, 50, 20],
    });
    console.log(data);

    chart.data(data);
    chart.scale('value', {
      alias: '销售额(万)',
    });

    chart.axis('type', {
      tickLine: {
        alignTick: false,
      },
    });
    chart.axis('value', false);

    chart.tooltip({
      showMarkers: false,
    });
    chart.interval().position('type*value');
    chart.interaction('element-active');

    // 添加文本标注
    data.forEach((item) => {
      chart
        .annotation()
        .text({
          position: [item.type, item.value],
          content: item.value,
          style: {
            textAlign: 'center',
          },
          offsetY: -30,
        })
        .text({
          position: [item.type, item.value],
          content: (item.percent * 100).toFixed(0) + '%',
          style: {
            textAlign: 'center',
          },
          offsetY: -12,
        });
    });
    chart.render();
    chartInstance.current = chart;

    return () => {
      // if(chartInstance.current){
      //   console.log(chartInstance.current,'container.current');
      //   chartInstance.current?.destory?.();
      // }
    };
  }, [data.length]);

  return <div style={{ height: 500 }} ref={el}></div>;
});

const DemoPie = () => {
  const data = [
    {
      type: '分类一',
      value: 27,
    },
    {
      type: '分类二',
      value: 25,
    },
    {
      type: '分类三',
      value: 18,
    },
    {
      type: '分类四',
      value: 15,
    },
    {
      type: '分类五',
      value: 10,
    },
    {
      type: '其他',
      value: 5,
    },
  ];
  const config = {
    appendPadding: 10,
    data,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.6,
    label: {
      type: 'inner',
      offset: '-50%',
      content: '{value}',
      style: {
        textAlign: 'center',
        fontSize: 14,
      },
    },
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
    ],
    statistic: {
      title: false,
      content: {
        style: {
          whiteSpace: 'pre-wrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
        },
        content: 'AntV\nG2Plot',
      },
    },
  };
  console.log('重新渲染');

  return <Pie {...config} />;
};

const A = ({ data }) => {
  const values = ['运行成功', '运行失败'];
  data.forEach((obj: any) => {
    // obj.range = [obj.startTime, obj.endTime];
    obj.range = [
      Number(new Date(obj.startTime)),
      Number(new Date(obj.endTime)),
    ];
    console.log(moment(obj.startTime).unix());

    obj.status = values[obj.status];
  });
  const min = Math.min(...data.map((item) => Number(new Date(item.range[0]))));
  const max = Math.max(...data.map((item) => Number(new Date(item.range[1]))));
  // const [chart,setChart] = useState(null);
  const config = {
    data,
    yField: 'task',
    // scrollbar: {
    //   type: 'vertical',
    // },//滚动条
    // slider: {
    //   //缩略轴
    //   start: 0,
    //   end: 1,
    // },
    // devicePixelRatio: 1,
    xField: 'range',
    // xAxis: {
    //   minLimit: min,//控制x轴最小值
    //   maxLimit: max ,
    //   // tickInterval: 86400000
    //   // tickMethod: 'time'
    // },
    // scale:{
    //   range: {
    //     type: 'time',
    //     nice: true,
    //   }
    // },
    isRange: true, //是否是区间图
    seriesField: 'status', //分类展示字段
    interactions: [
      {
        type: 'element-active', //鼠标在区间内显示阴影 一般和tooltip.shared = false,一起用
      },
    ],
    legend: {
      //分类展示按钮
      position: 'bottom',
    },
    color: (e) => {
      console.log(e);
      return e.status === '运行成功' ? '#FAAD14' : '#5B8FF9';
    },
    // minColumnWidth: 115,
    meta: {
      //配置元信息  字段名： 修改字段轴的label显示
      range: {
        minLimit: min, //控制x轴最小值
        maxLimit: max,
        formatter: (values, index) => {
          console.log(values, 'w');

          return moment(values).format('YYYY-MM-DD HH:mm:ss');
        },
      },
    },
    tooltip: {
      shared: false,
      showTitle: false,
      itemTpl: `
    <ul class="g2-tooltip-list">
      <li class="g2-tooltip-list-item">
        <span class="g2-tooltip-marker" style="background-color:{color}"></span>
        <span class="g2-tooltip-name">名称</span>
        <span class="g2-tooltip-value">{name}</span>
      </li>
      <li class="g2-tooltip-list-item">
        <span class="g2-tooltip-marker" style="background-color:{color}"></span>
        <span class="g2-tooltip-name">开始时间</span>
        <span class="g2-tooltip-value">{value1}</span>
      </li>
      <li class="g2-tooltip-list-item">
      <span class="g2-tooltip-marker" style="background-color:{color}"></span>
      <span class="g2-tooltip-name">结束时间</span>
      <span class="g2-tooltip-value">{value2}</span>
    </li>
    </ul/
    `,
      formatter: (datum: Datum) => {
        console.log(datum);
        return {
          name: datum.task,
          value1: moment(datum.range[0]).format('YYYY-MM-DD'),
          value2: moment(datum.range[1]).format('YYYY-MM-DD'),
          color: datum.status === '运行成功' ? '#FAAD14' : '#5B8FF9',
        };
      },
    },
    onReady: (plot) => {
      console.log(plot, plot.chart.coordinate);
      // plot.chart.coordinate().transpose();\
      // plot.chart.scale('range', {
      //   type: 'time',
      // });
      // setChart(plot);
      console.log(plot, plot.chart.coordinate);
      plot.on('plot:click', (evt) => {
        const { x, y } = evt;
        const { xField } = plot.options;
        const tooltipData = plot.chart.getTooltipItems({ x, y });
        console.log(tooltipData);
      });
    },
  };

  return <Bar {...config} />;
};
const B = React.memo(A, (prevProps, nextProps) => {
  // 返回false进行更新
  // 返回true不需要进行更新
  console.log({ prevProps, nextProps }, '11111111111');
  return JSON.stringify(prevProps) === JSON.stringify(nextProps);
});

const C = (props, ref) => {
  return React.createElement('div', {}, '11111');
};

const Charts: React.FC = () => {
  const [radio, setRadio] = useState('1');
  const [string, setString] = useState('string');
  const [data, setData] = useState([]);
  const options = [
    { label: 'Apple', value: '1' },
    { label: 'Pear', value: '2' },
  ];
  const a = useRef();
  // let data = [];

  useEffect(() => {
    loginService.getChart({ id: radio }).then((res) => {
      // setData(res.data);
      const data = [
        { type: '未知', value: 654, percent: 0.02 },
        { type: '17 岁以下', value: 654, percent: 0.02 },
        { type: '18-24 岁', value: 4400, percent: 0.2 },
      ];
      const data2 = [
        { type: '25-29 岁', value: 5300, percent: 0.24 },
        { type: '30-39 岁', value: 6200, percent: 0.28 },
        { type: '40-49 岁', value: 3300, percent: 0.14 },
        { type: '50 岁以上', value: 1500, percent: 0.06 },
      ];

      setData(radio === '1' ? data : data2);
    });
  }, [radio]);
  console.log(a, 'a');

  return (
    <div style={{ width: '100%' }}>
      <div>
        <Form>
          <Form.Item>
            <Input
              value={string}
              onChange={(e) => {
                setString(e.target.value);
              }}
            />
          </Form.Item>
        </Form>
      </div>

      <Card
        title={
          <div>
            <Radio.Group
              options={options}
              onChange={(e) => {
                console.log(e.target.value);
                setRadio(e.target.value);
              }}
              value={radio}
              optionType="button"
            />
          </div>
        }
      >
        {/* <B data={data} /> */}
        <DemoPie />
        <MyChart ref={a} data={data} />
        {/* <C /> */}
      </Card>
    </div>
  );
};

export default Charts;
